package question1;

public class CyclicAcquisition implements Runnable
{

	private Thread local;
	private Command<Float> command;

	private HumiditySensor sensor;
	private long period;

	public CyclicAcquisition( HumiditySensor sensor, long period,
			Command<Float> command ) throws Exception
			{
		if ( period < sensor.minimalPeriod() )
			throw new Exception( " respectez la periode minimale ( >= "
					+ sensor.minimalPeriod() + ") !!" );
		this.sensor= sensor;
		this.period= period;
		this.command= command;
		local= new Thread( this );
			} // CyclicAcquisition()

	public void start()
	{
		local.start();
	} // start()

	public void stop()
	{
		local.interrupt();
	} // stop()

	public synchronized void setPeriod( long period ) throws Exception
	{
		if ( period < sensor.minimalPeriod() )
			throw new Exception( " respectez la periode minimale ( >= "
					+ sensor.minimalPeriod() + ") !!" );
		this.period= period;
	} // setPeriod()

	public void run()
	{
		try {
			if ( Thread.currentThread() != local )
				throw new Exception( "Mauvais thread !!" );
			while ( !local.isInterrupted() ) {
				synchronized (this) {
					try {
						/* lecture du capteur et transmission de la valeur par make() */
						command.make(sensor.value());
					}
					catch ( Exception e ) {
						/* transmission d'une valeur negative par make() */
						command.make((float) -1);
					}
					Thread.sleep( period );
				} // synchronized
			} // while
		}
		catch ( InterruptedException ie ) {
			// rien
		}
		catch ( Exception e ) {
			System.out.println( e.toString() );
		} // catch
	} // run()
} // CyclicAcquisition
